package com.xneure.code;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.util.Map;
import com.xneure.utils.ObjectUtil;

public class NioServer extends NioSocket{
	 private Map<Integer,Object> clients = new CacheMap<Integer,Object>(20){
		private static final long serialVersionUID = -8295981379393852412L;

		@Override
		void init(boolean startTime){
			super.init(false);
			setCheckTime(500);
		}
		 
	 };
	 ServerSocketChannel serverChannel ;
	public void initServer(int port) throws IOException{
		serverChannel = ServerSocketChannel.open();
		serverChannel.configureBlocking(false);
		serverChannel.socket().bind(new InetSocketAddress(port));
		serverChannel.register(getSelector(),SelectionKey.OP_ACCEPT);
		listen();
	}

	public static void main(String[] args) throws IOException{
		NioServer nioServer = new NioServer();
		nioServer.initServer(9981);
		nioServer.disconnect();
	}

	@Override
	public void disconnect(){
		super.disconnect();
		ObjectUtil.callMethod(clients,"stopRefresh");
	}

	@Override
	void receiveMsg(byte[] data,int length){
		System.out.println(new String(data,0,length));
		sendObject("已接收");
	}

	@Override
	void event(SelectionKey key) throws IOException{
		if(key.isAcceptable()){
			ServerSocketChannel server = (ServerSocketChannel)key.channel();
			try{
				listenHandler(server.accept());
			}catch(IOException e){
			}
		}
	}
}
